//
//  NetworkMonitor.m
//  VideoPlayer
//
//  Created by 白璐 on 16/10/8.
//  Copyright © 2016年 baidu. All rights reserved.
//

#import "NetworkMonitor.h"

#import <CoreFoundation/CoreFoundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

@interface NetworkMonitor ()
@property(nonatomic, assign) SCNetworkReachabilityRef reachabilityRef;
@property(nonatomic, assign) SCNetworkReachabilityFlags lastFlags;
@property(nonatomic, assign) BOOL firstTime;
@end

@implementation NetworkMonitor

- (instancetype)init {
    if (self = [super init]) {
        _firstTime = YES;
    }
    
    return self;
}

- (void)dealloc {
    [self stop];
}

- (void)start {
    self.reachabilityRef = SCNetworkReachabilityCreateWithName(NULL, "www.baidu.com");
    SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL};
    if (SCNetworkReachabilitySetCallback(self.reachabilityRef, networkMonitorCallback, &context)) {
        SCNetworkReachabilityScheduleWithRunLoop(self.reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    }
}

- (void)stop {
    if (self.reachabilityRef) {
        SCNetworkReachabilityUnscheduleFromRunLoop(self.reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
        CFRelease(self.reachabilityRef);
        self.reachabilityRef = NULL;
    }
}

static void networkMonitorCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) {
    __weak NetworkMonitor* monitor = (__bridge NetworkMonitor*)info;
    
    NetworkType type = [monitor networkFromFlags:flags];
    
    if (monitor.firstTime) {
        monitor.firstTime = NO;
        monitor.lastFlags = flags;
        monitor.currentNetowrk = type;
        return;
    }
    
    if (flags == monitor.lastFlags) {
        return;
    }
    
    monitor.currentNetowrk = type;
    monitor.lastFlags = flags;
    if (monitor.networkChangedBlock) {
        monitor.networkChangedBlock(type);
    }
}

- (NetworkType)networkFromFlags:(SCNetworkReachabilityFlags)flags {
    if (flags & kSCNetworkReachabilityFlagsReachable) {
        if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
            return NetworkTypeWWAN;
        } else {
            return NetworkTypeWIFI;
        }
    } else {
        return NetworkTypeNone;
    }
}

@end
